<template>
	<div class="login-container" :style="{'backgroundImage': 'url('+bgLoginImg+')'}">
		<el-form class="loginForm" ref="loginForm" :model="loginForm" :rules="loginRules" auto-complete="on" label-position="left">
			<div class="loginForm-box flex justify-center align-center">
				<div class="loginForm-content">
					<!-- <div class="title-container">
						<h3 class="title">灯箱管理系统</h3>
					</div> -->
					<el-tabs v-model="activeName" type="border-card" @tab-click="handleClickTab">
						<el-tab-pane label="账号登录" name="username">
							<div class="loginForm-content-inner" v-if="activeName=='username'">
								<el-col :span="24">
									<el-form-item prop="username">
										<el-input ref="username" v-model="loginForm.username" placeholder="请输入账号" name="username" type="text"
										 tabindex="1" auto-complete="on">
											<template slot="prepend">
												<svg-icon icon-class="user" /> 账号</template>
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item prop="password">
										<el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="请输入密码"
										 name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin">
											<template slot="prepend">
												<svg-icon icon-class="password" /> 密码</template>
											<template slot="append">
												<div class="inline-flex justify-center align-center" style="width:100%;height:100%">
													<el-button type="text" @click.native="showPwd">
														<svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
													</el-button>
												</div>
											</template>
										</el-input>
									</el-form-item>
								</el-col>
								<el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登入
								</el-button>
							</div>
						</el-tab-pane>
						<el-tab-pane label="手机号登录" name="mobile">
							<div class="loginForm-content-inner" v-if="activeName=='mobile'">
								<div class="loginForm-content-inner">
									<el-col :span="24">
										<el-form-item prop="mobile">
											<el-input class="flex-grow" ref="mobile" v-model="loginForm.mobile" placeholder="请输入手机号" name="mobile" type="text"
											 tabindex="1" auto-complete="on">
												<template slot="prepend"><i class="el-icon-phone" /> 手机号</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :span="24">
										<el-form-item prop="image_code">
											<el-col :span="17">
												<el-input ref="image_code" v-model="loginForm.image_code" placeholder="请输入图片验证码" name="image_code" type="text"
												 tabindex="2">
													<template slot="prepend">
														<svg-icon icon-class="password" /> 图片验证码</template>
												</el-input>
											</el-col>
											<el-col :span="6" :offset="1" style="height: 40px;">
												<img :src="imageCodeData" @click="getImageCode">
											</el-col>
										</el-form-item>
									</el-col>
									<el-col :span="24">
										<el-form-item prop="code">
											<el-input ref="code" v-model="loginForm.code" placeholder="请输入验证码" name="code" type="text" tabindex="3">
												<template slot="prepend">
													<svg-icon icon-class="password" /> 短信验证码</template>
												<template slot="append">
													<div class="inline-flex justify-center align-center" style="width:100%;height:100%">
														<el-button class="margin-lr-xs" type="text" @click.native="getCode" :loading="getCodeLoading" :disabled="getCodeLoading || getCodeTimeCount>0">{{(getCodeLoading || getCodeTimeCount>0)?(getCodeTimeCount+'s后重试'):'获取验证码'}}</el-button>
													</div>
												</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleMobileLogin">登入
									</el-button>
								</div>
							</div>
						</el-tab-pane>
					</el-tabs>
				</div>

			</div>
		</el-form>
		<transition name="bv-box">
			<div class="bv-mask flex justify-center align-center" v-show="showBV">
				<div id="cbox"></div>
			</div>
		</transition>
		<div style="position: fixed;bottom: 0;width:100%" class="padding-xl flex justify-center align-center">
			<div class="text-white text-lg bg-white padding-lr-sm padding-tb-xs" style="border-radius: 3px;">
				ICP备案号：<a class="text-blue" href="https://beian.miit.gov.cn" target="_blank">苏ICP备2022017004号-1</a>
			</div>
		</div>
	</div>
</template>

<script>
	import bgLoginImg from '@/assets/images/bg_login.jpg'
	import {
		validUsername
	} from "@/utils/validate";
	import {
		Message
	} from 'element-ui';
	import {
		get_appId,
		behavior_verification
	} from '@/api/other/behavior_verification.js'
	import {
		get_image_code,
		check_send_sms
	} from '@/api/other/captcha.js'
	import {
		isFunction,
		isTrue
	} from '@/utils/util.js'

	export default {
		name: "Login",
		data() {
			return {
				bgLoginImg,
				activeName: 'username',

				imageCodeData: '',
				getCodeLoading: false,
				getCodeTimeCount: 0,
				GetCodeTimer: null,

				APPID: '',
				showBV: false,
				loginForm: {
					username: "",
					password: "",
					mobile: "",
					image_code: "",
					code: ""
				},
				loginRules: {
					username: [{
						required: true,
						trigger: "blur",
						message: "请输入账号"
					}],
					password: [{
						required: true,
						trigger: "blur",
						message: "请输入密码"
					}],
					mobile: [{
						required: true,
						trigger: "blur",
						message: "请输入手机号"
					}],
					code: [{
						required: true,
						trigger: "blur",
						message: "请输入验证码"
					}]
				},
				loading: false,
				passwordType: "password",
				redirect: undefined
			};
		},
		watch: {
			$route: {
				handler: function(route) {
					this.redirect = route.query && route.query.redirect;
				},
				immediate: true
			}
		},
		mounted() {
			//this.getAPPID()
			this.getImageCode()
		},
		methods: {
			getImageCode() {
				get_image_code().then(resp => {
					return 'data:image/png;base64,' + btoa(new Uint8Array(resp).reduce((data, byte) => data + String.fromCharCode(
						byte), ''))
				}).then(data => {
					this.imageCodeData = data
				})
			},
			/**
			 * 检查图片验证码
			 */
			checkImageCodeAndSendSMSCode() {
				this.getCodeLoading = true
				return check_send_sms({
						code: this.loginForm.image_code,
						mobile: this.loginForm.mobile
					})
					.then(res => {
						if (isTrue(res.data)) {
							Message.success("验证码已发送")
						} else {
							this.getCodeTimeCount = 0
							this.clearGetCodeInterval()
							Message.error(res.message)
						}
						this.getCodeLoading = false
					}).catch(() => {
						this.getCodeLoading = false
					})
			},
			handleClickTab(tab, event) {
				// console.log(tab, event);
			},
			getAPPID() {
				const that = this
				get_appId()
					.then(res => {
						that.APPID = res.data
					})
			},
			iniYpRiddler(appId) {
				const that = this
				// 初始化
				new YpRiddler({
					expired: 10,
					mode: 'flat',
					winWidth: 300,
					lang: 'zh-cn',
					container: document.getElementById('cbox'),
					appId: that.APPID,
					version: 'v1',
					onError: function(param) {
						if (!param.code) {
							console.error('错误请求');
						} else if (parseInt(param.code / 100) == 5) {
							// 服务不可用时，开发者可采取替代方案
							console.error('验证服务暂不可用');
						} else if (param.code == 429) {
							console.warn('请求过于频繁，请稍后再试');
						} else if (param.code == 403) {
							console.warn('请求受限，请稍后再试');
						} else if (param.code == 400) {
							console.warn('非法请求，请检查参数');
						}
						// 异常回调
						console.error('验证服务异常')
					},
					onSuccess: function(validInfo, close, useDefaultSuccess) {
						// 成功回调
						behavior_verification({
								token: validInfo.token,
								authenticate: validInfo.authenticate
							})
							.then(res => {
								if (isTrue(res.data)) {
									// 验证成功默认样式
									useDefaultSuccess(true)
									that.onLogin()
									close()
									that.showBV = false;
								} else {
									Message.error("验证失败")
									close()
									that.showBV = false;
								}
							})
							.catch(() => {
								close()
								that.showBV = false;
							})
					},
					onFail: function(code, msg, retry) {
						// 失败回调
						retry()
					},
					beforeStart: function(next) {
						next()
					}
				})
			},
			showPwd() {
				if (this.passwordType === "password") {
					this.passwordType = "";
				} else {
					this.passwordType = "password";
				}
				this.$nextTick(() => {
					this.$refs.password.focus();
				});
			},
			getCode() {
				const that = this
				const TIME_COUNT = 60; //倒计时60秒
				if (!this.loginForm.mobile) {
					Message.error('请输入手机号')
				} else if (!this.loginForm.image_code) {
					Message.error('请输入图片验证码')
				} else {
					if (!that.GetCodeTimer) {
						that.checkImageCodeAndSendSMSCode()
						that.getCodeTimeCount = TIME_COUNT;
						that.GetCodeTimer = setInterval(() => {
							if (that.getCodeTimeCount > 0 && that.getCodeTimeCount <= TIME_COUNT) {
								that.getCodeTimeCount--;
							} else {
								that.clearGetCodeInterval();
							}
						}, 1000);
					}
				}
			},
			clearGetCodeInterval(){
				const that = this
				clearInterval(that.GetCodeTimer);
				that.GetCodeTimer = null;
			},
			handleLogin() {
				const that = this
				that.$refs.loginForm.validate(valid => {
					if (valid) {
						//that.iniYpRiddler()
						//that.showBV = true;
						// 由于滑块服务开始收费，此处去除滑块验证
						that.onLogin()
					} else {
						console.log("error submit!!");
						return false;
					}
				});
			},
			handleMobileLogin() {
				this.$refs.loginForm.validate(valid => {
					if (valid) {
						this.onLogin("user/loginByMobile")
					} else {
						console.log("error submit!!");
						return false;
					}
				});
			},
			onLogin(dispatchName = "user/login") {
				const that = this;
				const pageLoading = this.$loading({
					lock: true,
					text: '登录中',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.6)'
				});
				that.loading = true;
				that.$store
				  .dispatch(dispatchName, that.loginForm)
				  .then(() => {
					that.$store.commit('company/RESET_COMPANY_INFO');
					that.clearGetCodeInterval();
				    that.$router.push({
				    	path: "/index"
				    });
					pageLoading.close()
				    that.loading = false;
				  })
				  .catch(() => {
					pageLoading.close()
				    that.loading = false;
				  });
			},
		}
	};
</script>

<style lang="scss">
	/* 修复input 背景不协调 和光标变色 */
	/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

	// $bg: #283443;
	// $light_gray: #fff;
	// $cursor: #fff;

	// @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
	// 	.login-container .el-input input {
	// 		color: $cursor;
	// 	}
	// }

	// /* reset element-ui css */
	// .login-container {
	// 	.el-input {
	// 		display: inline-block;
	// 		height: 47px;
	// 		width: 85%;

	// 		input {
	// 			background: transparent;
	// 			border: 0px;
	// 			-webkit-appearance: none;
	// 			border-radius: 0px;
	// 			padding: 12px 5px 12px 15px;
	// 			color: $light_gray;
	// 			height: 47px;
	// 			caret-color: $cursor;

	// 			&:-webkit-autofill {
	// 				box-shadow: 0 0 0px 1000px $bg inset !important;
	// 				-webkit-text-fill-color: $cursor !important;
	// 			}
	// 		}
	// 	}

	// 	.el-form-item {
	// 		border: 1px solid rgba(255, 255, 255, 0.1);
	// 		//background: rgba(0, 0, 0, 0.1);
	// 		border-radius: 5px;
	// 		color: #454545;
	// 	}
	// }
</style>

<style lang="scss" scoped>
	$bg: #2d3a4b;
	$dark_gray: #889aa4;
	$light_gray: #eee;

	.login-container {
		height: 100%;
		width: 100%;
		background-size: cover;
		background-color: $bg;
		overflow: hidden;

		.loginForm {
			height: 100%;
			width: 100%;

			.loginForm-box {
				position: relative;
				height: 100%;
				width: 100%;
				overflow: hidden;

				.loginForm-content {
					//background-color: $color-ghostWhite;
					padding: 0;
					border-radius: 10px;
					width: 550px;

					/deep/.el-tabs.el-tabs--top.el-tabs--border-card {
						//box-shadow: $shadow-size $color-darkGray;

						/deep/.el-tabs__content {
							padding: 20px 20px 0 !important;

							.loginForm-content-inner {
								// width: 450px;
							}
						}
					}
				}

			}
		}

		.tips {
			font-size: 14px;
			color: #fff;
			margin-bottom: 10px;

			span {
				&:first-of-type {
					margin-right: 16px;
				}
			}
		}

		.svg-container {
			padding: 6px 5px 6px 15px;
			color: $dark_gray;
			vertical-align: middle;
			width: 30px;
			display: inline-block;
		}

		.title-container {
			position: relative;

			.title {
				font-size: 26px;
				color: $light_gray;
				margin: 0px auto 40px auto;
				text-align: center;
				font-weight: bold;
			}
		}

		.show-pwd {
			position: absolute;
			right: 10px;
			top: 7px;
			font-size: 16px;
			color: $dark_gray;
			cursor: pointer;
			user-select: none;
		}

		.bv-mask {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.6);
			z-index: 3000;
		}

		.bv-box-enter-active {
			transition: opacity .3s ease;
		}

		.bv-box-leave-active {
			transition: opacity .3s ease;
		}

		.bv-box-enter {
			opacity: 0;
		}

		.bv-box-leave-to {
			opacity: 0;
		}
	}
</style>
